package com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.send;

import com.alibaba.fastjson.JSON;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.S30Config;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.S30Exception;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.channel.send.S30SendChannel;
import com.cetccloud.ap.util.IdUtil;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayEntityMessage;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayRegisterRequestHeader;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayRegisterRequestMessage;
import com.thunisoft.exchange.gateway.protocol.entity.RegisterAppNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName RegisterReqHandler
 * @Description 自动注册请求
 * @Author superz
 * @Date 2021/5/3 10:47
 * @Version 1.0
 **/
@Slf4j
@Component
public class RegisterReqHandler {

    @Autowired
    private S30Config s30Config;

    @Autowired
    private S30SendChannel s30SendChannel;

    public void handle() throws S30Exception {
        GatewayEntityMessage entityMessage = new GatewayEntityMessage();
        GatewayRegisterRequestHeader requestHeader = new GatewayRegisterRequestHeader();
        GatewayRegisterRequestMessage requestEntity = new GatewayRegisterRequestMessage();
        requestHeader.setRequestID(IdUtil.requestId());
        RegisterAppNode meta = new RegisterAppNode();
        meta.setName(s30Config.getProxy().getAppName());
        meta.setAlias(s30Config.getProxy().getAppAlias());
        meta.setIp(s30Config.getProxy().getAppIp() + s30Config.getProxy().getAppPort());
        requestEntity.setMeta(meta);
        entityMessage.setHeader(requestHeader);
        entityMessage.setEntity(requestEntity);

        log.info("自动注册请求... 请求: {}", JSON.toJSONString(entityMessage));

        boolean flag = s30SendChannel.asyncSend(entityMessage);
        if (!flag) {
            throw new S30Exception("S30Channel.asyncSend failed");
        }
    }
}
